package com.neusoft.zqygbc.neusoft_wenda.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.neusoft.zqygbc.neusoft_wenda.R;
import com.neusoft.zqygbc.neusoft_wenda.base.RetrofitCallback;
import com.neusoft.zqygbc.neusoft_wenda.javeBean.Status;
import com.neusoft.zqygbc.neusoft_wenda.model.UserModel;
import com.neusoft.zqygbc.neusoft_wenda.service.UserService;
import com.neusoft.zqygbc.neusoft_wenda.view.XCRoundImageView;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.neusoft.zqygbc.neusoft_wenda.model.Server.BASE_URL;


public class UserEditActivity extends BaseAvtivity {
    private Context context;
    private TextView edit_btn_save;
    private EditText edit_username,edit_email,edit_signature,edit_schoolname;
    private TextView text_birth, text_complete;
    private DatePicker dp_birthdate;
    private Spinner spn_sex;
    private XCRoundImageView upic;
    private LinearLayout useredit_return, ll_edit_upic;
    private UserModel userModel;
    private Call call;
    private RetrofitCallback<Status> updataCallback;
    Dialog mCameraDialog;
    private static final int IMAGE = 1;


    @Override
    void initViews() {
        setLayout(R.layout.activity_user_edit);
        ll_edit_upic = (LinearLayout) findViewById(R.id.ll_edit_upic);
        edit_username = (EditText) findViewById(R.id.edit_username);
        edit_email = (EditText) findViewById(R.id.edit_email);
        text_birth = (TextView) findViewById(R.id.text_birth);
        spn_sex = (Spinner) findViewById(R.id.spn_sex);
        edit_btn_save = (TextView) findViewById(R.id.edit_btn_save);
        useredit_return = (LinearLayout) findViewById(R.id.useredit_return);
        upic = (XCRoundImageView) findViewById(R.id.edit_upic);
        edit_signature = (EditText) findViewById(R.id.edit_signature);
        edit_schoolname = (EditText) findViewById(R.id.edit_schoolname);
    }

    @Override
    void initEvents() {
        spn_sex.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String[] gender = getResources().getStringArray(R.array.sex);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        text_birth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });
        useredit_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        edit_btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savedata();
            }
        });
        ll_edit_upic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /**
                 * 跳转到相册获取一张图片
                 * IMAGE图片数量
                 */
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE);
            }
        });

    }

    /**
     * 获取图片路径
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取图片路径
        if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            uploadFile(imagePath);
            c.close();
            uploadFile(imagePath);
        }
    }

    private void showDialog() {
        mCameraDialog = new Dialog(this, R.style.my_dialog);
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.date_alert_dialog, null);
        text_complete = (TextView) root.findViewById(R.id.text_complete);
        dp_birthdate = (DatePicker) root.findViewById(R.id.dp_birthdate);
        mCameraDialog.setContentView(root);
        text_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String birth = String.valueOf(dp_birthdate.getYear()) + "-" + String.valueOf(dp_birthdate.getMonth() + 1) + "-" + String.valueOf(dp_birthdate.getDayOfMonth());
                text_birth.setText(birth);
                mCameraDialog.dismiss();
            }
        });
        Window dialogWindow = mCameraDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialogWindow.setWindowAnimations(R.style.dialogstyle); // 添加动画
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = -20; // 新位置Y坐标
        lp.width = (int) getResources().getDisplayMetrics().widthPixels; // 宽度
//		lp.height = WindowManager.LayoutParams.WRAP_CONTENT; // 高度
//		lp.alpha = 9f; // 透明度
        root.measure(0, 0);
        lp.height = root.getMeasuredHeight();
        lp.alpha = 9f; // 透明度
        dialogWindow.setAttributes(lp);
        mCameraDialog.show();
    }

    private View.OnClickListener btnlistener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.text_complete: // 打开照相机

                    break;

            }
        }
    };


    @Override
    void initData() {
        Intent intent = getIntent();
        edit_username.setText(intent.getStringExtra("username"));
        edit_email.setText(intent.getStringExtra("email"));
        text_birth.setText(intent.getStringExtra("birth"));
        edit_signature.setText(intent.getStringExtra("signature"));
        edit_schoolname.setText(intent.getStringExtra("schoolname"));
        if (intent.getStringExtra("sex") != null) {
            if (intent.getStringExtra("sex").equals("男")) {
                spn_sex.setSelection(0, true);
            } else {
                spn_sex.setSelection(1, true);
            }
        }
        Picasso.with(context).load("http://115.159.93.244/wenda/Public/userphoto/" + intent.getStringExtra("upic")).into(upic);

    }

    private void savedata() {
        userModel = new UserModel();
        call = userModel.updatauserdata(getUser_id(),
                edit_username.getText().toString(),
                edit_email.getText().toString(),
                spn_sex.getSelectedItem().toString(),
                text_birth.getText().toString(),
                edit_signature.getText().toString(),
                edit_schoolname.getText().toString());
        updataCallback = new RetrofitCallback<Status>() {
            @Override
            public void onResponse(Status status) {

                if (status.getCode().equals("1")) {

                    Toast.makeText(UserEditActivity.this, "内容修改成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(UserEditActivity.this, MainActivity.class);
                    intent.putExtra("fragid", 4);
                    startActivity(intent);
                } else {

                    Toast.makeText(UserEditActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                }

            }

        };
        userModel.bindCallback(call, updataCallback);
    }

    /**
     * 文件上传
     *
     * @param filePath
     */
    private void uploadFile(String filePath) {
        Retrofit ret = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        UserService uservice = ret.create(UserService.class);
        final File file = new File(filePath);
//        Bitmap bm = BitmapFactory.decodeFile(filePath);
//        upic.setImageBitmap(bm);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("upic", file.getName(), requestFile);
        Call<ResponseBody> call = uservice.upload(body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {

                try {
                    Toast.makeText(UserEditActivity.this, "success", Toast.LENGTH_SHORT).show();
                    Log.e("Upload", "success:" + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("Upload error:", t.getMessage());
                Toast.makeText(UserEditActivity.this, "error", Toast.LENGTH_SHORT).show();
            }
        });
    }


}
